<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="file" id="file">
    <script>
        var eleFile = document.querySelector('#file');
        var reader = new FileReader(), img = new Image();
        var file = null;
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');

        reader.onload = function (e) {
            img.src = e.target.result;
        }

        img.onload = function () {
            var originWidth = this.width;
            var originHeight = this.height;
            // console.log(originWidth, originHeight)
            var maxWidth = 400, maxHeight = 400;
            var targetWidth = originWidth, targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                    targetHeight = maxHeight;
                    targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
            }
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            canvas.toBlob(function(blob) {
                console.log(blob);
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function() {
                    if (xhr.status === 200) {
                        console.log(xhr.responseText);
                    } 
                } //监听服务器响应
                xhr.open('POST', '/upload', true); //发送一个POST请求
                xhr.send(blob);
            })
            document.body.appendChild(canvas);
        }
        eleFile.addEventListener('change', function (event) {
            file = event.target.files[0];
            if (file.type.indexOf('image') == 0) {
                reader.readAsDataURL(file);
            }
        })


    </script>
</body>

</html>